//
//  CalenderView.m
//  YZCCalender
//
//  Created by Jason on 2018/1/17.
//  Copyright © 2018年 jason. All rights reserved.
//

#import "CalenderCollectionCell.h"
#import "CalenderHeaderView.h"
#import "CalenderModel.h"
#import "CalenderView.h"
#import "CalenderWeekView.h"
#import "NSDate+Extension.h"

@interface CalenderView ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray   *dataSource;
@property (nonatomic, strong) CalenderWeekView *weekView;

@property (nonatomic, copy) NSString *startDay;
@property (nonatomic, copy) NSString *endDay;
@property (nonatomic, copy) NSString *startSelectDay;
@property (nonatomic, copy) NSString *endSelectDay;

@property (nonatomic, strong) NSIndexPath *inIndexPath; // 入住的的indexPath
@property (nonatomic, strong) NSIndexPath *outIndexPath; // 退房的indexPath
@property (nonatomic, strong) NSMutableArray *betweenCellIndexPathList; // 间隙的数组

@end

static NSString *const reuseIdentifier  = @"collectionViewCell";
static NSString *const headerIdentifier = @"headerIdentifier";

@implementation CalenderView

- (instancetype)initWithFrame:(CGRect)frame
                     startDay:(NSString *)startDay
                       endDay:(NSString *)endDay
               startSelectDay:(NSString *)startSelectDay
                 endSelectDay:(NSString *)endSelectDay {
    self = [super initWithFrame:frame];
    if (self) {
        self.startDay = startDay;
        self.endDay   = endDay;
        self.startSelectDay = startSelectDay;
        self.endSelectDay = endSelectDay;
        [self buildSource];
        [self addSubview:self.weekView];
        [self.weekView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.offset(0);
            make.height.offset(32.0);
        }];
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.weekView.mas_bottom);
            make.left.bottom.right.offset(0);
        }];
    }
    return self;
}

#pragma mark - 设置数据源
- (void)buildSource {
    NSAssert(self.startDay.length && self.endDay.length, @"开始时间和结束时间不能为空");
    if (!self.startDay.length || !self.endDay.length) {
        self.startDay = [NSDate timeStringWithInterval:[NSDate date].timeIntervalSince1970];
        self.endDay   = [NSDate timeStringWithInterval:[NSDate date].timeIntervalSince1970];
    }
    
    NSArray   *startArray = [self.startDay componentsSeparatedByString:@"-"];
    NSArray   *endArray   = [self.endDay componentsSeparatedByString:@"-"];
    NSInteger month       = ([endArray[0] integerValue] - [startArray[0] integerValue])* 12 + ([endArray[1] integerValue] - [startArray[1] integerValue]) + 1;
    
    for (int i = 0; i < month; i++) {
        NSMutableArray *array = [[NSMutableArray alloc]init];
        [self.dataSource addObject:array];
    }
    
    for (int i = 0; i < month; i++) {
        int              calcNumberMonth = (int)[NSDate month:self.startDay] + i;
        int              month           = (calcNumberMonth)%12;
        NSDateComponents *components     = [[NSDateComponents alloc]init];
        
        //获取下个月的年月日信息,并将其转为date
        components.month = month ? month : 12;
        components.year  = [startArray[0] integerValue] + (calcNumberMonth == 12 ? 0 : calcNumberMonth) / 12;
        components.day   = 1;
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate     *nextDate = [calendar dateFromComponents:components];
        
        //获取该月第一天星期几
        NSInteger firstDayInThisMounth = [NSDate firstWeekdayInThisMonth:nextDate];
        
        //该月的有多少天daysInThisMounth
        NSInteger daysInThisMounth = [NSDate totaldaysInMonth:nextDate];
        NSString  *string          = [[NSString alloc]init];
        for (int j = 0; j < (daysInThisMounth > 29 && (firstDayInThisMounth == 6 || firstDayInThisMounth == 5) ? 42 : 35); j++) {
            CalenderModel *model = [[CalenderModel alloc] init];
            model.year  = components.year;
            model.month = components.month;
            if (j < firstDayInThisMounth || j > daysInThisMounth + firstDayInThisMounth - 1) {
                string    = @"";
                model.day = string;
            } else {
                string    = [NSString stringWithFormat:@"%02ld", j - firstDayInThisMounth + 1];
                model.day = string;
                
                NSString *dateStr = [NSString stringWithFormat:@"%zd-%02zd-%@", model.year, model.month, model.day];
                if ([self isActivity:dateStr]) {
                    model.enableSelect = YES;;
                } else {
                    model.enableSelect = NO;
                }
            }
            
            // 根据之前选中的数据来赋值inIndexPath和outIndexPath
            if (![MSSafeObject isNull:self.startSelectDay]) {
                NSString *totalStr = [NSString stringWithFormat:@"%04ld-%02ld-%@", model.year, model.month, model.day];
                if ([totalStr isEqualToString:self.startSelectDay]) {
                    model.selectType = 2;
                    self.inIndexPath = [NSIndexPath indexPathForItem:j inSection:i];
                } else if ([totalStr isEqualToString:self.endSelectDay]) {
                    model.selectType = 3;
                    self.outIndexPath = [NSIndexPath indexPathForItem:j inSection:i];
                }
            }
            
            [[self.dataSource objectAtIndex:i]addObject:model];
        }
    }
    if (self.inIndexPath) {
        [self caculateBetweenCellWithInIndexPath:self.inIndexPath outIndexPat:self.outIndexPath];
    }
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataSource.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *sectionList = [self.dataSource objectAtIndex:section];
    return [sectionList count];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CalenderModel *model = self.dataSource[indexPath.section][indexPath.item];
    
    if (!model.day.length) {
        return;
    }
    NSString *selectDate = [NSString stringWithFormat:@"%04ld-%02ld-%@", model.year, model.month, model.day];
    if (![self isActivity:selectDate]) {
        return;
    }
    
    // 判断当前是否有inIndexPath
    // 0-入住 2-退房
    NSInteger inOutStatus = 0;
    if ((!self.inIndexPath && !self.outIndexPath) ||
        self.inIndexPath && self.outIndexPath) {
        // 之前没有设置过有效的入住和退房日期或者有设置过有效的入住和退房日期
        if (self.inIndexPath && self.outIndexPath) {
            // 如果之前设置过入住和退房，需要将之前选中和中间的cell的状态都修改
            [self changeModelSelectModelIndePath:self.inIndexPath SelectType:0];
            [self changeModelSelectModelIndePath:self.outIndexPath SelectType:0];

            for (NSIndexPath *betweenIndex in self.betweenCellIndexPathList) {
                [self changeModelSelectModelIndePath:betweenIndex SelectType:0];
            }
            [self.betweenCellIndexPathList removeAllObjects];
            self.inIndexPath = nil;
            self.outIndexPath = nil;
        }
        // 当前选中的cell为入住的位置
        inOutStatus = 0;
    } else {
        // 之前只有一个选中了
        // 需要判断时间的大小
        CalenderModel *lastModel = self.dataSource[self.inIndexPath.section][self.inIndexPath.item];
        NSString *lastSelectDate = [NSString stringWithFormat:@"%04ld-%02ld-%@", lastModel.year, lastModel.month, lastModel.day];
        NSComparisonResult result = [selectDate compare:lastSelectDate];
        if (result == NSOrderedSame) {
            return;
        } else if (result == NSOrderedDescending) {
            // 新的比原来的晚
            inOutStatus = 2;
            // 计算补充间隙cell
            [self caculateBetweenCellWithInIndexPath:self.inIndexPath outIndexPat:indexPath];
        } else if (result == NSOrderedAscending) {
            // 新的比原先的早
            inOutStatus = 0;
            // 将原来的cell改成默认状态
            [self changeModelSelectModelIndePath:self.inIndexPath SelectType:0];
        }
    }
    if (inOutStatus == 0) {
        self.inIndexPath = indexPath;
        [self changeModelSelectModelIndePath:indexPath SelectType:2];
    } else {
        self.outIndexPath = indexPath;
        [self changeModelSelectModelIndePath:indexPath SelectType:3];
    }
    // 刷新数据
    [self.collectionView reloadData];
    if (self.delegate && [self.delegate respondsToSelector:@selector(refreshDoneStatus:)]) {
        [self.delegate refreshDoneStatus:(inOutStatus == 2)];
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CalenderCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    NSLog(@"indexPath: section:%ld item:%ld", indexPath.section, indexPath.item);
    CalenderModel *model = self.dataSource[indexPath.section][indexPath.item];
    cell.model = model;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        CalenderHeaderView *heardView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
        CalenderModel      *model     = self.dataSource[indexPath.section][indexPath.item];
        heardView.yearAndMonthLabel.text = [NSString stringWithFormat:self.yearMonthFormat.length ? self.yearMonthFormat : @"%zd年%zd月", model.year, model.month];
        heardView.yearAndMonthLabel.textColor = [UIColor blackColor];
        return heardView;
    } else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"calenderFooter" forIndexPath:indexPath];
        footer.backgroundColor = rgb(242, 242, 242);
        return footer;
    }
    
    return nil;
}

#pragma mark - Public Method

- (void)refreshCollectionViewWithStartSelectDay:(NSString *)startSelectDay endSelectDay:(NSString *)endSelectDay {
    
    
}

- (NSString *)newStartSelectDay {
    CalenderModel *model = self.dataSource[self.inIndexPath.section][self.inIndexPath.item];
    NSString *startDay = [NSString stringWithFormat:@"%04ld-%02ld-%@", model.year, model.month, model.day];
    return startDay;
}

- (NSString *)newEndSelectDay {
    CalenderModel *model = self.dataSource[self.outIndexPath.section][self.outIndexPath.item];
    NSString *endDay = [NSString stringWithFormat:@"%04ld-%02ld-%@", model.year, model.month, model.day];
    return endDay;
}


#pragma mark - Private Method
/** 计算中间cell */
- (void)caculateBetweenCellWithInIndexPath:(NSIndexPath *)inIndexPath outIndexPat:(NSIndexPath *)outIndexPath {
    NSInteger inSection = inIndexPath.section;
    NSInteger inItem = inIndexPath.item;
    NSInteger outSection = outIndexPath.section;
    NSInteger outItem = outIndexPath.item;
    for (NSInteger i = inSection; i <= outSection; i ++) {
        NSArray *sectionList = self.dataSource[i];
        NSInteger sectionCount = sectionList.count;
        if ((inSection == outSection ) && (inItem + 1 == outItem) ){
            // 入住和退房在同一组，且相隔,不需要betweencell
            break;
        }
        // 遍历添加中间cell
        NSInteger tempI = (i == inSection)?(inItem + 1):0;
        NSInteger tempMax = (i == outSection)?outItem:sectionCount;
        for (NSInteger j = tempI; j < tempMax; j ++) {
            NSIndexPath *tempIndex = [NSIndexPath indexPathForItem:j inSection:i];
            [self.betweenCellIndexPathList addObject:tempIndex];
            [self changeModelSelectModelIndePath:tempIndex SelectType:1];
        }
    }
}
/** 修改model的选中类型 */
- (void)changeModelSelectModelIndePath:(NSIndexPath *)indexPath SelectType:(NSInteger)selectType {
    CalenderModel *model = (CalenderModel *)self.dataSource[indexPath.section][indexPath.item];
    model.selectType = selectType;
    self.dataSource[indexPath.section][indexPath.item] = model;
}

#pragma mark - set

- (void)setWeekBottomLineColor:(UIColor *)weekBottomLineColor {
    _weekBottomLineColor              = weekBottomLineColor;
    self.weekView.weekBottomLineColor = weekBottomLineColor;
}

- (void)setShowWeekBottomLine:(BOOL)showWeekBottomLine {
    _showWeekBottomLine    = showWeekBottomLine;
    self.weekView.showLine = showWeekBottomLine;
}

- (BOOL)isActivity:(NSString *)date {
    BOOL activity = NO;
    
    NSTimeInterval startInterval   = [NSDate timeIntervalFromDateString:[NSString stringWithFormat:@"%@ 00:00:00", self.startDay]];
    NSTimeInterval endInterval     = [NSDate timeIntervalFromDateString:[NSString stringWithFormat:@"%@ 00:00:00", self.endDay]];
    NSTimeInterval currentInterval = [NSDate timeIntervalFromDateString:[NSString stringWithFormat:@"%@ 00:00:00", date]];
    
    if (currentInterval >= startInterval && currentInterval <= endInterval) {
        activity = YES;
    }
    return activity;
}

#pragma mark - lazy
- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        float                      cellw       = MS_SCREEN_WIDTH / 7;
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        [flowLayout setHeaderReferenceSize:CGSizeMake(MS_SCREEN_WIDTH, 50)];
        flowLayout.sectionInset            = UIEdgeInsetsMake(0, -1, 0, 0);
        flowLayout.minimumInteritemSpacing = -1;
        flowLayout.minimumLineSpacing      = 0;
        flowLayout.itemSize                = CGSizeMake(cellw, 50);
        flowLayout.headerReferenceSize = CGSizeMake(MS_SCREEN_WIDTH, 25);
        flowLayout.footerReferenceSize = CGSizeMake(MS_SCREEN_WIDTH, 10);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero  collectionViewLayout:flowLayout];
        
        _collectionView.dataSource                     = self;
        _collectionView.delegate                       = self;
        _collectionView.showsVerticalScrollIndicator   = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        [_collectionView registerClass:[CalenderHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"calenderFooter"];
        [_collectionView registerClass:[CalenderCollectionCell class] forCellWithReuseIdentifier:reuseIdentifier];
        _collectionView.backgroundColor = [UIColor whiteColor];
    }
    return _collectionView;
}

- (CalenderWeekView *)weekView {
    if (_weekView == nil) {
        _weekView            = [[CalenderWeekView alloc] init];
        _weekView.dataSource = self.weekArray ? self.weekArray : @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"];
    }
    return _weekView;
}

- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)betweenCellIndexPathList {
    if (!_betweenCellIndexPathList) {
        _betweenCellIndexPathList = [NSMutableArray array];
    }
    return _betweenCellIndexPathList;
}

@end

